﻿using Microsoft.Azure;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Configuration;

namespace Microsoft.Cloud.API.Azure.Services
{
    public static class ADALService
    {
        public static Uri ServiceManagementUrl
        {
            get
            {
                return new Uri(ConfigurationManager.AppSettings["serviceManagementUrl"]);
            }
        }

        public static string StorageDomainSuffix
        {
            get
            {
                return ConfigurationManager.AppSettings["storageDomainSuffix"];
            }
        }

        public static SubscriptionCloudCredentials GetCredential(string subscriptionId)
        {
            //var credentials = new CertificateCloudCredentials(
            //    subscriptionId: subscriptionId,
            //    managementCertificate: new X509Certificate2(Convert.FromBase64String(ConfigurationManager.AppSettings["certificate"])));

            var token = GetAuthorizationHeader();

            var credentials = new TokenCloudCredentials(subscriptionId, token);

            return credentials;
        }

        private static string GetAuthorizationHeader()
        {
            var context = new AuthenticationContext(ConfigurationManager.AppSettings["authorityUrl"]);

            // Directly specify the username and password. 
            var credential = new UserCredential(ConfigurationManager.AppSettings["authUserName"], ConfigurationManager.AppSettings["authUserPassword"]);
            var result = context.AcquireToken(ConfigurationManager.AppSettings["serviceManagementUrl"], ConfigurationManager.AppSettings["clientId"], credential);

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            return result.AccessToken;
        }
    }
}